package com.lihonghao.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;


@Configuration
public class RedisConfig {
    @Value("${spring.redis.host:localhost}")
    String redisHost;
    @Value("${spring.redis.port:6379}")
    int redisPort;
    @Value("${spring.redis.password:lihonghao233}")
    String redisPassword;
    @Value("${spring.redis.database:1}")
    int redisDatabase;
    @Value("${spring.redis.timeout:3000}")
    int redisTimeout;

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory();
        lettuceConnectionFactory.setHostName(redisHost);
        lettuceConnectionFactory.setPort(redisPort);
        if (redisPassword != null && !redisPassword.isEmpty()) {
            lettuceConnectionFactory.setPassword(redisPassword);
        }
        lettuceConnectionFactory.setDatabase(redisDatabase);
        lettuceConnectionFactory.setTimeout(redisTimeout);
        return lettuceConnectionFactory;
    }

    @Bean({"redisTemplate"})
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate redis = new RedisTemplate();
        GenericToStringSerializer<String> keySerializer = new GenericToStringSerializer(String.class);
        redis.setKeySerializer(keySerializer);
        redis.setHashKeySerializer(keySerializer);
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        redis.setValueSerializer(valueSerializer);
        redis.setHashValueSerializer(valueSerializer);
        redis.setConnectionFactory(connectionFactory);
        return redis;
    }
}

